package com.mediacloud.app.newsmodule.fragment.newslist;

import java.util.ArrayList;
import java.util.List;

import com.androidkun.xtablayout.DividerDrawable;
import com.androidkun.xtablayout.XTabLayout;
import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.mediacloud.app.assembly.adapter.CatalogContentFragmentAdapter;
import com.mediacloud.app.assembly.adapter.IAdapterTitle;
import com.mediacloud.app.assembly.util.Reflect;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.assembly.views.RadioButtonX;
import com.mediacloud.app.model.fragment.INaviateState;
import com.mediacloud.app.model.utils.DefaultBgUtil;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.model.fragment.BaseNavigateFragment;
import com.mediacloud.app.newsmodule.utils.AppThemeTabLayoutStyle;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.reslib.enums.Navigate;

import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Parcelable;

import androidx.annotation.CallSuper;

import com.google.android.material.tabs.TabLayout;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager.widget.ViewPager;

import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RadioGroup;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;

/**
 * 顶部带栏目结构的fragment
 */
@SuppressWarnings("deprecation")
public abstract class TableCatalogItemsFragmentBase<E extends Parcelable & IAdapterTitle> extends BaseNavigateFragment implements ViewPager.OnPageChangeListener {
    //    protected RadioButtonGroupX mCatalogGroupContainer;
    protected SlidingTabLayout mCatalogItemContainer;
    protected ViewPager mContentViewPager;
    protected List<E> navigateItems;
    protected CatalogContentFragmentAdapter contentFragmentAdapter;
    public static final String Catatlogs = "catalogs";
    protected View topContainer;
    protected float appfactory_topcatalog_unchecked_textsize;
    protected float appfactory_topcatalog_checked_textsize;
    public int lastSelectIndex = -1;
    //	protected Navigate navigate;
    protected Navigate mNavigate;

    public boolean hadChooseZero = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        appfactory_topcatalog_unchecked_textsize = getResources().getDimension(R.dimen.appfactory_topcatalog_unchecked_textsize);///getResources().getDisplayMetrics().density;
        appfactory_topcatalog_checked_textsize = getResources().getDimension(R.dimen.appfactory_topcatalog_checked_textsize);///getResources().getDisplayMetrics().density;
    }

    @Override
    public void initView() {
        mContentViewPager = Utility.findViewById(mRootView, R.id.mContentViewPager);
        mCatalogItemContainer = mRootView.findViewById(R.id.mCatalogItemContainer);
        mCatalogItemContainer.setTextSelectColor(Color.parseColor("#333333"));
        mCatalogItemContainer.setTextUnselectColor(Color.parseColor("#666666"));
//        mCatalogGroupContainer = mRootView.findViewById(R.id.mCatalogGroupContainer);
        int color = getResources().getColor(R.color.style_blue);
        mCatalogItemContainer.setIndicatorColor(color);
       // setTabLayoutGap(requireContext(),mCatalogItemContainer);
        topContainer = mRootView.findViewById(R.id.topContainer);
        getArgs();
        setListener();
        initTableView();
//        createRadioButtonItems();
        setTabLayoutData();
    }

    public static void setTabLayoutGap(Context context, XTabLayout tabLayout) {
        int space = AppFactoryGlobalConfig.getAppServerConfigInfo(context).getNavigate_show_spacing();
        if (space > 0) {
            if (!Utility.isAdMachine(context))
                space = Utility.dpToPx(context, space / 3.0f);
            else
                space = (int) (space / 2.5f);
        } else {
            space = context.getResources().getDimensionPixelSize(R.dimen.appfactory_topcatalog_btnmargin);
        }
        tabLayout.setDividerSize(space / 2, 0);
        tabLayout.setDividerColor(Color.TRANSPARENT);
        tabLayout.setDividerGravity(DividerDrawable.CENTER);
    }
    protected void setTabLayoutData() {
        final ArrayList<Fragment> list = new ArrayList<Fragment>();

        for (int i = 0; navigateItems != null && i < navigateItems.size(); i++) {
            //加按钮对应的fragment
            Fragment fragment = getViewContentFragment(navigateItems.get(i));
            if (fragment != null) {
                list.add(fragment);
            }
        }
        try {
            if (list.size() > 0) {
                //如果子项只有一个table  那就把上面的tableNavigate隐藏掉
                setCatalogItemContentList(getChildFragmentManager(), list);
                List<IAdapterTitle> titleList = new ArrayList<>();
                titleList.addAll(navigateItems);
                contentFragmentAdapter.titleList = titleList;
               // AppThemeTabLayoutStyle.setTabLayoutStyle(getActivity(), mCatalogItemContainer, TabLayout.MODE_SCROLLABLE);
                mCatalogItemContainer.setViewPager(mContentViewPager);
            }
        } catch (Exception e) {
            if (e != null) {
                e.printStackTrace();
                Log.e(TAG, e.getMessage() + "");
            }
        }
    }

    @Override
    public void setArguments(Bundle args) {
        super.setArguments(args);
    }

    protected void initTableView() {

    }

    protected void getArgs() {
        try {
            if (getFragmentArguments() != null) {
                navigateItems = getFragmentArguments().getParcelableArrayList(Catatlogs);
                //				navigate=(Navigate) getFragmentArguments().getSerializable("navigate");
            } else if (getActivity() != null) {
                navigateItems = getActivity().getIntent().getParcelableArrayListExtra(Catatlogs);
                //				navigate=(Navigate) getActivity().getIntent().getSerializableExtra("navigate");
            }

            if (navigateItems == null) {
                navigateItems = new ArrayList<E>();
                if (getFragmentArguments() != null) {
                    E catalogItem = getFragmentArguments().getParcelable("catalog");
                    navigateItems.add(catalogItem);
                } else if (getActivity() != null) {
                    E catalogItem = getActivity().getIntent().getParcelableExtra("catalog");
                    navigateItems.add(catalogItem);
                }
            }

            if (mNavigate == null) {
                mNavigate = (Navigate) getFragmentArguments().getSerializable("navigate");

                Log.i("test", "mNavigate:" + mNavigate);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, e.getMessage());
        }
    }

    protected void setListener() {
        mContentViewPager.setOnPageChangeListener(this);
    }

    @Override
    public void onPageSelected(int index) {
        if (contentFragmentAdapter != null) {
          /*  RadioButtonX radioButtonX = (RadioButtonX) mCatalogGroupContainer.getChildAt(index);
            if (radioButtonX.isChecked() == false)
                radioButtonX.setChecked(true);*/
            choosedIndexNavigate(index);
        }
    }

    protected void choosedIndexNavigate(int index) {
        if (!isChoosed || contentFragmentAdapter == null)
            return;
        Fragment item = contentFragmentAdapter.getItem(index);
        if (item != null && item instanceof INaviateState) {
            ((INaviateState) item).choosed();
            for (Fragment collectionItem : contentFragmentAdapter.getList()) {
                if (collectionItem != null && collectionItem instanceof INaviateState && collectionItem != item) {
                    ((INaviateState) collectionItem).unChosoed();
                }
            }
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageScrollStateChanged(int arg0) {
    }

   /* protected void invalidateRadioButtonsPadding() {
        int margin = *//*getResources().getDimensionPixelSize(R.dimen.appfactory_topcatalog_btnmargin)*//*0;
        int containerWidth = topContainer.getMeasuredWidth();
        int scrollerWidth = mCatalogItemContainer.getMeasuredWidth();
        int gap = containerWidth - scrollerWidth;
        if (gap < 0)
            gap = 0;
        final int maxWidth = mCatalogGroupContainer.invalidatePadding2(margin, gap, false);
        final int top = mCatalogItemContainer.getTop();
        if (Utility.isBirdLanguageConfig(getActivity()))
            mCatalogItemContainer.postDelayed(new Runnable() {
                @Override
                public void run()
                {
                    arabicModeScroll();
                }
            }, 500);
    }*/

    /* */

    /**
     * 根据栏目列表长度  创建相应个数的子fragment
     *//*
    public void createRadioButtonItems() {
        mCatalogGroupContainer.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {

            @Override
            public boolean onPreDraw() {
                mCatalogGroupContainer.getViewTreeObserver().removeOnPreDrawListener(this);
                if (getActivity() != null)
                    invalidateRadioButtonsPadding();
                return true;
            }
        });
        final List<Fragment> list = new ArrayList<Fragment>();

        for (int i = 0; navigateItems != null && i < navigateItems.size(); i++) {
            final int index = i;
            //加按钮
            final RadioButtonX radioButtonX = createRadioButtonItem(navigateItems.get(i));
            RadioGroup.LayoutParams lp = getItemRadioButtonLayoutParams();
            radioButtonX.setTextSize(TypedValue.COMPLEX_UNIT_PX, appfactory_topcatalog_unchecked_textsize);
            radioButtonX.setOnCheckedChangeListener(getRadioButtonCheckeChangedListener(radioButtonX, index));
            radioButtonX.updateEffDrawable();
            mCatalogGroupContainer.addView(radioButtonX, lp);
            //加按钮对应的fragment
            Fragment fragment = getViewContentFragment(navigateItems.get(i));
            if (fragment != null) {
                list.add(fragment);
            }
        }
        try {
            if (list.size() > 0) {
                RadioButton radioButton = ((RadioButton) mCatalogGroupContainer.getChildAt(0));
                radioButton.setChecked(true);
                //如果子项只有一个table  那就把上面的tableNavigate隐藏掉
                setCatalogItemContentList(getChildFragmentManager(), list);
            }
        } catch (Exception e) {

            e.printStackTrace();
            Log.e(TAG, e.getMessage());
        }

    }*/
    protected RadioGroup.LayoutParams getItemRadioButtonLayoutParams() {
        RadioGroup.LayoutParams lp = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.MATCH_PARENT);
        lp.gravity = Gravity.CENTER;
        return lp;
    }

    protected RadioButtonCheckeChangedListener getRadioButtonCheckeChangedListener(RadioButtonX radioButtonX, int index) {
        return new RadioButtonCheckeChangedListener(radioButtonX, index);
    }

    abstract public Fragment getViewContentFragment(E catalogItem);

    protected RadioButtonX createRadioButtonItem(E catalogItem) {
        final RadioButtonX radioButtonX = new RadioButtonX(getActivity());
        radioButtonX.setGravity(Gravity.CENTER);
        radioButtonX.setSingleLine(true);

        radioButtonX.uncheckedDrawable = new ColorDrawable(Color.TRANSPARENT);
        radioButtonX.checkedDrawable = new ColorDrawable(Color.TRANSPARENT);
        radioButtonX.drawableType = RadioButtonX.bottom;
        //		radioButtonX.setText(catalogItem.getCatname());
        return radioButtonX;
    }

    @CallSuper
    protected void setCatalogItemContentList(FragmentManager manager, ArrayList<Fragment> list) {
        contentFragmentAdapter = new CatalogContentFragmentAdapter(manager, list);
        lastSelectIndex = 0;
        mContentViewPager.setAdapter(contentFragmentAdapter);
        mContentViewPager.setCurrentItem(0);
        mContentViewPager.setOffscreenPageLimit(1);
        onPageSelected(0);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mRootView.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (lastSelectIndex != -1) {
                    if (Utility.isBirdLanguageConfig(getActivity()))
                        arabicModeScroll();
                    else
                        normalModeScroll();
                }
            }
        }, 100);
    }

    protected class RadioButtonCheckeChangedListener implements OnCheckedChangeListener {
        protected final RadioButtonX radioButtonX;
        protected final int index;

        public RadioButtonCheckeChangedListener(RadioButtonX radioButtonX, int index) {
            this.radioButtonX = radioButtonX;
            this.index = index;
        }
        @Override
        public synchronized void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                lastSelectIndex = index;
                scroll2ChoosedIndex();
            }
        }

        protected final void scroll2ChoosedIndex() {
            if (getActivity() != null) {
                if (Utility.isBirdLanguageConfig(getActivity()))
                    arabicModeScroll();
                else
                    normalModeScroll();
            }

        }

    }

    private void normalModeScroll() {

       /* int top = mCatalogItemContainer.getTop();
        mContentViewPager.setCurrentItem(lastSelectIndex);
        if (mCatalogItemContainer.getMeasuredWidth() == 0)
            return;
        int selfWidth = mCatalogGroupContainer.getChildAt(lastSelectIndex).getMeasuredWidth();
        RadioGroup.LayoutParams layoutParams = (LayoutParams) mCatalogGroupContainer.getChildAt(lastSelectIndex).getLayoutParams();
        if (!mCatalogGroupContainer.isPaddingMode() & layoutParams != null) {
            selfWidth += (layoutParams.getMarginStart() + layoutParams.getMarginEnd());
        }
        mCatalogItemContainer.computeScroll();
        int totalReverse = mCatalogGroupContainer.getRadionButtonPostionWidthReverse(lastSelectIndex);
        int halfContainerValue = (mCatalogItemContainer.getMeasuredWidth() - selfWidth) / 2;
        int leftReverse = mCatalogGroupContainer.getMeasuredWidth() - selfWidth - totalReverse;
        mCatalogItemContainer.smoothScrollTo(leftReverse - halfContainerValue, top);*/

    }

    private void arabicModeScroll() {
       /* int top = mCatalogItemContainer.getTop();
        mContentViewPager.setCurrentItem(lastSelectIndex);
        if (mCatalogItemContainer.getMeasuredWidth() == 0)
            return;
        int selfWidth = mCatalogGroupContainer.getChildAt(lastSelectIndex).getMeasuredWidth();
        RadioGroup.LayoutParams layoutParams = (LayoutParams) mCatalogGroupContainer.getChildAt(lastSelectIndex).getLayoutParams();
        if (!mCatalogGroupContainer.isPaddingMode() & layoutParams != null) {
            selfWidth += (layoutParams.getMarginStart() + layoutParams.getMarginEnd());
        }
        mCatalogItemContainer.computeScroll();
        int totalReverse = mCatalogGroupContainer.getRadionButtonPostionWidthReverse(lastSelectIndex);
        int halfContainerValue = (mCatalogItemContainer.getMeasuredWidth() - selfWidth) / 2;
        mCatalogItemContainer.smoothScrollTo(totalReverse - halfContainerValue, top);*/
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (navigateItems != null)
            navigateItems.clear();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        if (navigateItems != null) {
            ArrayList<E> tableList = new ArrayList<E>();
            tableList.addAll(navigateItems);
            outState.putParcelableArrayList(Catatlogs, tableList);
        }
        super.onSaveInstanceState(outState);
    }


    protected boolean isChoosed = false;

    @Override
    public void choosed() {
        isChoosed = true;
    }

    @Override
    public void unChosoed() {
        isChoosed = false;
    }
}